package io.gitee.sfch.chunmi.service.system.impl;


import cn.hutool.core.util.StrUtil;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryChain;
import io.gitee.sfch.chunmi.Tables;
import io.gitee.sfch.chunmi.common.enums.StatusEnum;
import io.gitee.sfch.chunmi.exception.DataAlreadyExistsException;
import io.gitee.sfch.chunmi.controller.system.form.SystemProductAddForm;
import io.gitee.sfch.chunmi.dao.system.entity.SystemProduct;
import io.gitee.sfch.chunmi.dao.system.mapper.SystemProductMapper;
import io.gitee.sfch.chunmi.entity.Pageable;
import io.gitee.sfch.chunmi.entity.Pagination;
import io.gitee.sfch.chunmi.service.system.SystemProductService;
import io.gitee.sfch.chunmi.service.system.converter.SystemProductConverter;
import io.gitee.sfch.chunmi.util.PageUtil;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

/**
 * {@link SystemProductService} 实现
 */
@Service
public class SystemProductServiceImpl implements SystemProductService {

    @Resource
    private SystemProductMapper systemProductMapper;
    @Resource
    private SystemProductConverter systemProductConverter;

    @Override
    public Pagination<SystemProduct> findPage(SystemProduct productParams, Pageable pageable) {
        Page<SystemProduct> page = QueryChain.of(systemProductMapper)
                .where(Tables.systemProduct.productCode.like(productParams.getProductCode()))
                .where(Tables.systemProduct.productName.like(productParams.getProductName()))
                .where(Tables.systemProduct.description.like(productParams.getDescription()))
                .where(Tables.systemProduct.status.eq(productParams.getStatus()))
                .orderBy(Tables.systemProduct.id.desc())
                .page(PageUtil.from(pageable));

        return PageUtil.from(page, pageable);
    }

    @Override
    public void addProduct(SystemProductAddForm command) {
        SystemProduct systemProduct = systemProductConverter.of(command);
        // 校验编码、名称是否重复
        if (systemProductMapper.isProductCodeExists(command.getProductCode())) {
            throw new DataAlreadyExistsException(StrUtil.format("产品编码已存在：{}", command.getProductCode()));
        }
        if (systemProductMapper.isProductNameExists(command.getProductName())) {
            throw new DataAlreadyExistsException(StrUtil.format("产品名称已存在：{}", command.getProductName()));
        }
        systemProduct.setStatus(StatusEnum.enabled);
        systemProductMapper.insert(systemProduct);
    }
}
